package com.example.administrator.rxjavarxandroid_retrofit.http.rxjava;

import android.content.Context;

import com.example.administrator.rxjavarxandroid_retrofit.http.exception.ApiError;
import com.example.administrator.rxjavarxandroid_retrofit.http.exception.CodeException;
import com.example.administrator.rxjavarxandroid_retrofit.http.exception.HttpTimeException;
import com.example.administrator.rxjavarxandroid_retrofit.http.factory.FactoryException;
import com.example.administrator.rxjavarxandroid_retrofit.util.ToastUtil;

import java.lang.ref.WeakReference;

import dmax.dialog.SpotsDialog;
import rx.Subscriber;

/**
 * Created by Administrator on 2016/12/14.
 */
public abstract class HttpObserver<T> extends Subscriber<T> implements onRequestListener<T> {

    //    回调接口
    //private HttpOnNextListener mSubscriberOnNextListener;
    //    弱引用防止内存泄露
    private WeakReference<Context> mActivity;
    //    是否能取消请求
    private boolean cancel;
    //    加载框可自己定义
    private SpotsDialog mDialog = null;

    public HttpObserver(WeakReference<Context> mActivity) {
        this.mActivity = mActivity;
        initProgressDialog();
    }

    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        /*需要緩存并且本地有缓存才返回*/
        errorDo(e);
        dismissProgressDialog();
    }

    @Override
    public void onHttpError(ApiError error) {
        //这里可以做错误处理，也可以在调用的时候重写error方法，对错误信息进行处理
        ApiError error1 = FactoryException.analysisExcetpion(error);
        ToastUtil.showToastLong(mActivity.get(),error.getDisplayMessage());
    }

    /**
     * 错误统一处理
     *
     * @param e
     */
    private void errorDo(Throwable e) {
        Context context = mActivity.get();
        //if (context == null) return;
        if (e instanceof ApiError) {
            onError((ApiError) e);
        } else if (e instanceof HttpTimeException) {
            HttpTimeException exception=(HttpTimeException)e;
            onError(new ApiError(exception, CodeException.RUNTIME_ERROR,exception.getMessage()));
        } else {
            onError(new ApiError(e, CodeException.UNKNOWN_ERROR,e.getMessage()));
        }
        /*可以在这里统一处理错误处理-可自由扩展*/

    }


    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    private void initProgressDialog() {
        Context context = mActivity.get();
        if (mDialog == null && context != null) {
            mDialog = new SpotsDialog(context,"正在加载中...");
        }
    }

    private void showProgressDialog() {
        Context context = mActivity.get();
        if (mDialog == null || context == null) return;
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    private void dismissProgressDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

}
